package alert

import (
	"context"
	"encoding/json"
	"errors"

	"yunzhan/alert-server/internal/svc"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateAlertRuleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewCreateAlertRuleLogic 新增告警规则
func NewCreateAlertRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateAlertRuleLogic {
	return &CreateAlertRuleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateAlertRuleLogic) CreateAlertRule(req *types.CreateAlertRuleRequest) (resp *types.CreateAlertRuleResponse, err error) {

	resp = &types.CreateAlertRuleResponse{
		CreatedRules: []*types.AlertRule{},
	}

	for _, rule := range req.AlertRules {
		// 验证必填字段
		if rule.ComponentName == "" || rule.Metric == "" || rule.Operator == "" {
			errMsg := "component, metric, and operator 字段不能为空"
			logx.Error(errMsg)
			return &types.CreateAlertRuleResponse{
				Success: 500,
				Message: "Validation error",
				Error:   errMsg,
			}, errors.New(errMsg)
		}

		// 将 notification_config 转换为 JSON 格式
		notificationConfigJSON, err := json.Marshal(rule.NotificationConfig)
		if err != nil {
			logx.Errorf("failed to marshal notification config: %v", err)
			return &types.CreateAlertRuleResponse{
				Success: 500,
				Message: "Failed to marshal notification config",
				Error:   err.Error(),
			}, err
		}

		alertRule := &types.AlertRule{
			ComponentName:      rule.ComponentName,
			ComponentRole:      rule.ComponentRole,
			Metric:             rule.Metric,
			Operator:           rule.Operator,
			Threshold:          rule.Threshold,
			Enabled:            rule.Enabled,
			NotificationConfig: string(notificationConfigJSON),
			Description:        rule.Description,
		}

		// 插入规则到数据库
		result, err := l.svcCtx.AlertRuleModel.Insert(alertRule)
		if err != nil {
			logx.Errorf("failed to insert alert rule: %v", err)
			return &types.CreateAlertRuleResponse{
				Success: 500,
				Message: "创建告警规则失败",
				Error:   err.Error(),
			}, err
		}

		id, err := result.LastInsertId()
		if err != nil {
			logx.Errorf("failed to retrieve last insert id: %v", err)
			return &types.CreateAlertRuleResponse{
				Success: 500,
				Message: "Failed to retrieve last insert id",
				Error:   err.Error(),
			}, err
		}

		alertRule.ID = id

		resp.CreatedRules = append(resp.CreatedRules, alertRule)
		logx.Infof("Successfully created alert rule, ID: %d", alertRule.ID)
	}

	// 设置响应的成功状态和消息
	resp.Success = 200
	resp.Message = "告警规则创建成功"

	// 返回响应对象
	return resp, nil

}
